package sched

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"pdocker/tool/sql"
	"time"

	log "github.com/sirupsen/logrus"
)

func (t *TaskTable) Select() bool {

	result := sql.PgDB.First(t)

	if result.Error != nil {
		log.Warningln(result.Error)
	}
	exists := result.RowsAffected
	return (exists > 0)
}

func (t *TaskTable) Insert() bool {
	log.Infof("t=%+v %T", t, t)
	result := sql.PgDB.Create(t)

	if result.Error != nil {
		log.Errorf("insert error %+v", result)
		return false
	}
	return true
}

func (t *TaskTable) Update(ts int64) {
	err := sql.PgDB.Model(t).Update("data", t.Data)
	if err != nil {
		log.Errorf("update error")

	}
}

func (t *TaskTable) Create() error {
	log.Debugf("==scheds create %+v", t)
	if t.Select() {
		return fmt.Errorf("this task exist: %s", t.TaskID)
	} else {
		t.Insert()
		return nil
	}

}

func (t *TaskTable) Start() {
	ok, timer := t.Timer(t.TimeStamp)
	log.Infof("sched start %v", ok)
	if ok {
		timerList[t.TaskID] = timer
	}
}

func (t *TaskTable) Delete() {
	// delete table
	sql.PgDB.Delete(t)

	// delete timer
	timerList[t.TaskID] = nil
}

func (t *TaskTable) Timer(timestamp int64) (bool, *time.Timer) {
	duration := time.Until(time.Unix(timestamp, 0))
	if duration < 0 {
		return false, nil
	}
	return true, time.AfterFunc(duration, func() {
		b, err := json.Marshal(t)
		if err != nil {
			log.Warningln(err)
		}
		resp, err := http.Post(t.CallBack, "application/json;charset=utf-8", bytes.NewBuffer(b))
		log.Infof("curl err= %+v", err)
		log.Infof("resp= %+v", resp)
		t.Delete()
	})
}

func (t *TaskTable) TableName() string {
	return "time_task_table"
}
